<?php

namespace Admin\Model\DBO;

use Zend\Db\TableGateway\AbstractTableGateway;
use Admin\Entity\Article;

class ArticleDBO extends AbstractTableGateway {

    private $sm;
    private $articleTable;

    public function __construct($serviceManager) {
        $this->sm = $serviceManager;
    }

    public function getArticleTable() {
        if (!$this->articleTable) {
            $this->articleTable = $this->sm->get('Admin\Model\DAO\ArticleTable');
        }
        return $this->articleTable;
    }

    public function fetchAll() {
        $iteratorAdapter = new \Zend\Paginator\Adapter\Iterator($this->getArticleTable()->fetchAll());
        $paginator = new \Zend\Paginator\Paginator($iteratorAdapter);
        return $paginator;
    }

    public function getArticle($articleID) {
        return $this->getArticleTable()->getArticle($articleID);
    }

    public function getAllArticlePublish($isPublish, $subCategoryID) {
        $iteratorAdapter = new \Zend\Paginator\Adapter\Iterator($this->getArticleTable()->getAllArticlePublish($isPublish, $subCategoryID));
        $paginator = new \Zend\Paginator\Paginator($iteratorAdapter);
        return $paginator;
    }
    public function getNewArticle($isPublisher, $subCategoryID, $numberArticle) {
        $iteratorAdapter = new \Zend\Paginator\Adapter\Iterator($this->getArticleTable()->getNewArticle($isPublisher, $subCategoryID, $numberArticle));
        $paginator = new \Zend\Paginator\Paginator($iteratorAdapter);
        return $paginator;
    }
     public function getListNewArticle($isPublisher, $subCategoryID, $numberArticle, $dateCreated) {
        $iteratorAdapter = new \Zend\Paginator\Adapter\Iterator($this->getArticleTable()->getListNewArticle($isPublisher, $subCategoryID, $numberArticle, $dateCreated));
        $paginator = new \Zend\Paginator\Paginator($iteratorAdapter);
        return $paginator;
    }
    public function saveArticle(Article $article) {
        $dateCreated = new \DateTime($article->dateCreated);
        $article->setDateCreated($dateCreated->format('Y-m-d'));
        return $this->getArticleTable()->saveArticle($article);
    }

    public function updateArticle(Article $article, $articleID) {
        $dateCreated = new \DateTime($article->dateCreated);
        $article->setDateCreated($dateCreated->format('Y-m-d'));
        return $this->getArticleTable()->updateArticle($article, $articleID);
    }

    public function deleteArticle($articleID) {
        $this->getArticleTable()->deleteArticle($articleID);
    }

    public function changeStatusPublishArticle($articleID, $status) {
        if ($this->getArticleTable()->getArticle($articleID)) {
            $this->getArticleTable()->changeStatusPublishArticle($articleID, $status);
            return true;
        }
        return false;
    }

}

?>
